{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "24057ba3",
   "metadata": {},
   "source": [
    "#  1. 百度AI开放平台  -OCR（光学字符识别）  \n",
    "#  2. 学生实践周  \n",
    "##  2.1 通用文字识别   \n",
    "     * 接口描述\n",
    "     > 在通用文字识别的基础上，提供更高精度的识别服务，支持更多语种识别（丹麦语、荷兰语、马来语、瑞典语、印尼语、波兰语、罗马尼亚语、土耳其语、希腊语、匈牙利语、泰语、越语、阿拉伯语、印地语及部分中国少数民族语言），并将字库从1w+扩展到2w+，能识别所有常用字和大部分生僻字。\n",
    "    "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "id": "a8702b67",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'refresh_token': '25.1903e261a7ff26dc18365a55f5877329.315360000.1965126635.282335-25954508', 'expires_in': 2592000, 'session_key': '9mzdD0LzVv0S+AUNN4pS/oWZ+lVmxvkdY8z/Apu+6RUV8AcW3zXTlYquZq9MPHoyEhX3J4zCcD2/mmiwXrqaH8Jmtn3xFw==', 'access_token': '24.4ff36a3402ddbd8068f683c7306a9a42.2592000.1652358635.282335-25954508', 'scope': 'public vis-ocr_ocr brain_ocr_scope brain_ocr_general brain_ocr_general_basic vis-ocr_business_license brain_ocr_webimage brain_all_scope brain_ocr_idcard brain_ocr_driving_license brain_ocr_vehicle_license vis-ocr_plate_number brain_solution brain_ocr_plate_number brain_ocr_accurate brain_ocr_accurate_basic brain_ocr_receipt brain_ocr_business_license brain_solution_iocr brain_qrcode brain_ocr_handwriting brain_form brain_ocr_passport brain_ocr_vat_invoice brain_numbers brain_ocr_business_card brain_ocr_train_ticket brain_ocr_taxi_receipt vis-ocr_household_register vis-ocr_vis-classify_birth_certificate vis-ocr_台湾通行证 vis-ocr_港澳通行证 vis-ocr_机动车购车发票识别 vis-ocr_机动车检验合格证识别 vis-ocr_车辆vin码识别 vis-ocr_定额发票识别 vis-ocr_保单识别 vis-ocr_机打发票识别 vis-ocr_行程单识别 brain_ocr_vin brain_ocr_quota_invoice brain_ocr_birth_certificate brain_ocr_household_register brain_ocr_HK_Macau_pass brain_ocr_taiwan_pass brain_ocr_vehicle_invoice brain_ocr_vehicle_certificate brain_ocr_air_ticket brain_ocr_invoice brain_ocr_insurance_doc brain_formula brain_seal brain_ocr_facade brain_ocr_meter brain_doc_analysis brain_ocr_webimage_loc brain_ocr_medical_paper brain_ocr_doc_analysis_office brain_vat_invoice_verification brain_ocr_medical_detail brain_vehicle_registration_certificate brain_ocr_online_taxi_itinerary brain_ocr_multi_idcard brain_ocr_mixed_multi_vehicle brain_ocr_weigth_note brain_ocr_ multiple_invoice wise_adapt lebo_resource_base lightservice_public hetu_basic lightcms_map_poi kaidian_kaidian ApsMisTest_Test权限 vis-classify_flower lpq_开放 cop_helloScope ApsMis_fangdi_permission smartapp_snsapi_base smartapp_mapp_dev_manage iop_autocar oauth_tp_app smartapp_smart_game_openapi oauth_sessionkey smartapp_swanid_verify smartapp_opensource_openapi smartapp_opensource_recapi fake_face_detect_开放Scope vis-ocr_虚拟人物助理 idl-video_虚拟人物助理 smartapp_component smartapp_search_plugin avatar_video_test b2b_tp_openapi b2b_tp_openapi_online', 'session_secret': 'bc992bcd39b855a3ee63efbf3e075623'}\n"
     ]
    }
   ],
   "source": [
    "# encoding:utf-8\n",
    "import requests \n",
    "\n",
    "# client_id 为官网获取的AK， client_secret 为官网获取的SK\n",
    "host = 'https://aip.baidubce.com/oauth/2.0/token?'\n",
    "# 准备url参数（酬载）\n",
    "payload = {\n",
    "    'grant_type':'client_credentials',\n",
    "    'client_id':'s1XWWYCw78Ia7UyKkGURjyKN',\n",
    "    'client_secret':'T7DIUAVKs50yruTSAN9RvbKttOZwx2Ox',\n",
    "    \n",
    "    \n",
    "}\n",
    "response = requests.get(host,params=payload)\n",
    "\n",
    "if response:\n",
    "    print(response.json())\n",
    "    access_token = response.json()['access_token']\n",
    "    "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e0d742f6",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "id": "ac1e0165",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'words_result': [{'words': '你的'}, {'words': '有多'}, {'words': '快乐'}, {'words': '明天'}, {'words': '不是'}, {'words': '我的，'}, {'words': '我们'}, {'words': '的爱是唱一半'}, {'words': '的歌'}], 'words_result_num': 9, 'log_id': 1513856470747672718}\n"
     ]
    }
   ],
   "source": [
    "import requests\n",
    "import base64\n",
    "\n",
    "request_url = \"https://aip.baidubce.com/rest/2.0/ocr/v1/accurate_basic\"\n",
    "# 二进制方式打开图片文件\n",
    "f = open('TY1.jpg', 'rb')\n",
    "img = base64.b64encode(f.read())\n",
    "\n",
    "payload = {\"image\":img,\n",
    "\"access_token\" : access_token,}\n",
    "headers = {'content-type': 'application/x-www-form-urlencoded'}\n",
    "response = requests.post(request_url, data=payload, headers=headers)\n",
    "if response:\n",
    "    print (response.json())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "719c31f3",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "id": "856948fa",
   "metadata": {},
   "source": [
    "##  2.2 网络图片字体识别"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "id": "ff55f330",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'words_result': [{'words': '爱情本身就是'}, {'words': '前人种树后人乘凉'}], 'words_result_num': 2, 'log_id': 1513859580372859015}\n"
     ]
    }
   ],
   "source": [
    "## 实践A-2\n",
    "\n",
    "\n",
    "import requests\n",
    "import base64\n",
    "\n",
    "request_url = \"https://aip.baidubce.com/rest/2.0/ocr/v1/webimage\"\n",
    "# 二进制方式打开图片文件\n",
    "f = open('WL.jpg', 'rb')\n",
    "img = base64.b64encode(f.read())\n",
    "\n",
    "payload = {\"image\":img,\n",
    "\"access_token\" : access_token,}\n",
    "headers = {'content-type': 'application/x-www-form-urlencoded'}\n",
    "response = requests.post(request_url, data=payload, headers=headers)\n",
    "if response:\n",
    "    print (response.json())"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9c528bf5",
   "metadata": {},
   "source": [
    "## 2.3 手写文字识别"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "id": "3da0c30d",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'words_result': [{'location': {'top': 73, 'left': 16, 'width': 1467, 'height': 520}, 'words': '你要储蓄你的可爱'}, {'location': {'top': 375, 'left': 83, 'width': 1158, 'height': 425}, 'words': '眷顾你的善良'}, {'location': {'top': 669, 'left': 106, 'width': 852, 'height': 371}, 'words': '变得勇敢'}, {'location': {'top': 671, 'left': 145, 'width': 1847, 'height': 620}, 'words': '当这个世界越来越坏时'}, {'location': {'top': 938, 'left': 245, 'width': 1798, 'height': 596}, 'words': '只期待你能越来越好'}, {'location': {'top': 1415, 'left': 1363, 'width': 642, 'height': 71}, 'words': '知平@阿娜娜斯小面包'}], 'words_result_num': 6, 'log_id': 1513860082141405174}\n"
     ]
    }
   ],
   "source": [
    "## 实践A-3\n",
    "\n",
    "\n",
    "import requests\n",
    "import base64\n",
    "\n",
    "request_url = \"https://aip.baidubce.com/rest/2.0/ocr/v1/handwriting\"\n",
    "# 二进制方式打开图片文件\n",
    "f = open('SX.jpg', 'rb')\n",
    "img = base64.b64encode(f.read())\n",
    "\n",
    "payload = {\"image\":img,\n",
    "\"access_token\" : access_token,}\n",
    "headers = {'content-type': 'application/x-www-form-urlencoded'}\n",
    "response = requests.post(request_url, data=payload, headers=headers)\n",
    "if response:\n",
    "    print (response.json())"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "64fe34a6",
   "metadata": {},
   "source": [
    "## 2.4 二维码识别  \n",
    "草料二维码生成器：https://cli.im/"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "id": "a3b5d951",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'codes_result': [{'text': ['世界，你好！'], 'type': 'QR_CODE'}], 'codes_result_num': 1, 'log_id': 1513860635576954321}\n"
     ]
    }
   ],
   "source": [
    "## 实践A-4\n",
    "\n",
    "\n",
    "import requests\n",
    "import base64\n",
    "\n",
    "request_url = \"https://aip.baidubce.com/rest/2.0/ocr/v1/qrcode\"\n",
    "# 二进制方式打开图片文件\n",
    "f = open('EWM.png', 'rb')\n",
    "img = base64.b64encode(f.read())\n",
    "\n",
    "payload = {\"image\":img,\n",
    "\"access_token\" : access_token,}\n",
    "headers = {'content-type': 'application/x-www-form-urlencoded'}\n",
    "response = requests.post(request_url, data=payload, headers=headers)\n",
    "if response:\n",
    "    print (response.json())"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "636326a3",
   "metadata": {},
   "source": [
    "## 2.5卡片类文字识别"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "id": "8a80f4bf",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'log_id': 1513862236637050001, 'error_msg': 'missing required parameter(s)', 'error_code': 282003}\n"
     ]
    }
   ],
   "source": [
    "## 实践A-5  身份证 & 银行卡\n",
    "\n",
    "import requests\n",
    "import base64\n",
    "\n",
    "request_url = \"https://aip.baidubce.com/rest/2.0/ocr/v1/idcard\"\n",
    "# 二进制方式打开图片文件\n",
    "f = open('SFZ.jpg', 'rb')\n",
    "img = base64.b64encode(f.read())\n",
    "\n",
    "payload = {\"image\":img,\n",
    "\"access_token\" : access_token,}\n",
    "headers = {'content-type': 'application/x-www-form-urlencoded'}\n",
    "response = requests.post(request_url, data=payload, headers=headers)\n",
    "if response:\n",
    "    print (response.json())"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "66124689",
   "metadata": {},
   "source": [
    "##  2.6财务类文字识别-增值税发票识别"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "id": "cb9cf3cf",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'words_result': [{'result': {'AmountInWords': [{'word': '壹仟贰佰捌拾圆整'}], 'InvoiceNumConfirm': [{'word': '08871892'}], 'CommodityEndDate': [], 'CommodityVehicleType': [], 'CommodityStartDate': [], 'CommodityPrice': [{'row': '1', 'word': '1094.017094'}], 'NoteDrawer': [{'word': '郭安邦'}], 'SellerAddress': [{'word': '杭州拱墅区金华路88号尚品商务楼538室0571-88291369'}], 'CommodityNum': [{'row': '1', 'word': '1'}], 'SellerRegisterNum': [{'word': '330100694585751'}], 'MachineCode': [], 'Remarks': [{'word': '网络发票号为:335376846311查验比对:您可通过wwwzjtax.gov,cn或纳税服务平石香验比对发票内容与税务局申报内容是否一致,以免不一致造成的后果'}], 'SellerBank': [{'word': '工行杭州拱宸支行1202020819900062790'}], 'CommodityTaxRate': [{'row': '1', 'word': '17%'}], 'TotalTax': [{'word': '185.98'}], 'InvoiceCodeConfirm': [{'word': '3300103620'}], 'CheckCode': [{'word': '72394820331130796309'}], 'InvoiceCode': [{'word': '3300103620'}], 'InvoiceDate': [{'word': '2011年06月27日'}], 'PurchaserRegisterNum': [], 'InvoiceTypeOrg': [{'word': '浙江增值税普通发票'}], 'OnlinePay': [], 'Password': [{'word': '<6>958317<*4+-5+1327+-7/*64>2115994831/9258<99/<9843960302126<0871<9943*/3750<+-7/*64>2115994831771*78779>95'}], 'Agent': [{'word': '否'}], 'AmountInFiguers': [{'word': '1280.00'}], 'PurchaserBank': [], 'Checker': [], 'City': [], 'TotalAmount': [{'word': '1094.02'}], 'CommodityAmount': [{'row': '1', 'word': '1094.02'}], 'PurchaserName': [{'word': '个人'}], 'CommodityType': [{'row': '1', 'word': 'GX98'}], 'Province': [{'word': '浙江'}], 'InvoiceType': [{'word': '普通发票'}], 'SheetNum': [{'word': '第二联：发票联'}], 'PurchaserAddress': [], 'CommodityTax': [{'row': '1', 'word': '185.98'}], 'CommodityPlateNum': [], 'CommodityUnit': [{'row': '1', 'word': '台'}], 'Payee': [], 'CommodityName': [{'row': '1', 'word': 'GPS行车安全警示器'}], 'SellerName': [{'word': '杭州征服者汽车用品有限公司'}], 'InvoiceNum': [{'word': '08871892'}]}, 'top': 4, 'left': 8, 'probability': 0.9988430738, 'width': 989, 'type': 'vat_invoice', 'height': 579}], 'words_result_num': 1, 'log_id': 1513863102060835804}\n"
     ]
    }
   ],
   "source": [
    "import requests\n",
    "import base64\n",
    "\n",
    "request_url = \"https://aip.baidubce.com/rest/2.0/ocr/v1/multiple_invoice\"\n",
    "# 二进制方式打开图片文件\n",
    "f = open('1.JPG', 'rb')\n",
    "img = base64.b64encode(f.read())\n",
    "\n",
    "payload = {\"image\":img,\n",
    "\"access_token\" : access_token,}\n",
    "headers = {'content-type': 'application/x-www-form-urlencoded'}\n",
    "response = requests.post(request_url, data=payload, headers=headers)\n",
    "if response:\n",
    "    print (response.json())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a8d51483",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.8"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
